package com.wiken.userservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wiken.servicecommon.common.Code;
import com.wiken.servicecommon.common.TokenUtil;
import com.wiken.servicecommon.common.exception.DefaultException;
import com.wiken.userservice.entity.Administrator;
import com.wiken.userservice.mapper.AdministratorMapper;
import com.wiken.userservice.service.IAdministratorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wiken
 * @since 2023-01-18
 */
@Service
public class AdministratorServiceImpl extends ServiceImpl<AdministratorMapper, Administrator> implements IAdministratorService {

    @Override
    public String login(Administrator administrator) {
        String password = administrator.getPassword();

        //将密码加密
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();

        administrator = baseMapper.selectOne(new QueryWrapper<Administrator>().eq("username", administrator.getUsername()));

        boolean success = bCryptPasswordEncoder.matches(password, administrator.getPassword());

        if(!success) throw new DefaultException(Code.ERROR_LOGIN_PWD_USERNAME, "账号或密码错误");
        if(administrator == null) throw new DefaultException(Code.ERROR_LOGIN_PWD_USERNAME, "账号或密码错误");

        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", administrator.getId());
        claims.put("authorities", "user");

        String token = TokenUtil.createToken(claims);

        return token;
    }
}
